package com.logistic.action;


import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.logistic.common.MyDateUtil;
import com.logistic.common.UidGeneratorByRule;
import com.logistic.domain.Integral;
import com.logistic.domain.User;
import com.logistic.domain.Waybill;
import com.logistic.page.PageView;
import com.logistic.page.QueryResult;
import com.logistic.service.IntegralService;
import com.logistic.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private UserService userService;
	private IntegralService integralService;
	

	private String Uid;
	private String UreceiveId;
	private String Uemail;
	private String Upassword;
	private String Uname;
	private String Utelephone;
	private String UcontactAdress;
	private String Uzip;
	private String UwangwangNum;
	private String UQQNum;
	private String UmsnNum;
	private String Unote;
	private String UregisterTime;
	private String UrecommendId;
	private String UrecommendBonusFlag;
	
	private Log log = LogFactory.getFactory().getLog(getClass());
	
	public String alipayBack(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		String Uid = (String)session.getAttribute("Uid");
		if(Uid!=null && !"".equals(Uid))
		return "backSuccess";
		else
		return null;
	}

	public void login() {
		
		log.info("Enter login action");
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		//response for ajax callback
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType( "text/html" ); 
	    response.setCharacterEncoding( "UTF-8" );
		

		User user = new User();
		user.setUemail((String)request.getAttribute("Uemail"));
		user.setUpassword((String)request.getAttribute("Upassword"));
		
		log.info("------User Email-------- =" + (String)request.getAttribute("Uemail"));
		log.info("------User IP-------- =" + request.getRemoteHost());
		
		User checkUser = userService.checkLogin(user);
		try{
			if (checkUser==null) {
				response.getWriter().print("{success:false}");
			}else
			{
				response.getWriter().print("{success:true}");
				
				session.setAttribute("Uid", checkUser.getUid());
				session.setAttribute("Uemail",checkUser.getUemail());
				session.setAttribute("UisManager",checkUser.getUisManager());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void checkEmailExist()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		String email = (String)request.getAttribute("Uemail");
		String ee = (String)request.getParameter("Uemail");
		if(email == null || "".equals(email))
		{
			email = ee;
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType( "text/html" ); 
	    response.setCharacterEncoding( "UTF-8" );
	    if(email == null || "".equals(email))
	    {
	    	log.error("email is null !");
	    }
	    
	    try {
			if(userService.checkEmailExist(email)){
				response.getWriter().print("{success:false,message:'failed'}");
				return;
			}
			response.getWriter().print("{success:true,message:'ok'}");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String register()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		String flag = request.getParameter("flagAdmin");
		User user = new User();
		String uId = UidGeneratorByRule.getUid();
		String uReceiveId = UidGeneratorByRule.getUreceiveId();
		while(userService.checkUidExist(uId))
		{
			uId = UidGeneratorByRule.getUid();
		}
		while(userService.checkUreceveIdExist(uReceiveId))
		{
			uReceiveId = UidGeneratorByRule.getUreceiveId();
		}
		user.setUid(uId);
		user.setUreceiveId(uReceiveId);
		user.setUemail(Uemail);
		user.setUname(Uname);
		user.setUtelephone(Utelephone);
		user.setUpassword(Upassword);
		
		if(request.getSession().getAttribute("recommendId") != null) {
			user.setUrecommendId((String) request.getSession().getAttribute("recommendId"));
			user.setUrecommendBonusFlag("N");
		}
		
		
		if(flag!=null && "".equals(flag) && "admin".equals(flag)){
			user.setUisManager("Y");
		}else{
			user.setUisManager("N");
		}
		user.setUregisterTime(MyDateUtil.getStringDate());
		userService.save(user);
		//注册送30积分
		Integral in = new Integral();
		in.setUid(uId);
		in.setPoint("0");
		
		in.setUsedPoints("0");
		in.setaccoutMoney("0");
		in.setUsedMoney("0");
		integralService.save(in);
		request.setAttribute("registerFlag", "SUCCESS");
		return "registerSuccess";
	}
	
	public String modify()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		String Uid = (String) request.getAttribute("Uid");
		
		User user = new User();
		user.setUid(Uid);
		user.setUemail(this.getUemail());
		user.setUpassword(this.getUpassword());
		user.setUname(this.getUname());
		user.setUtelephone(this.getUtelephone());
		user.setUcontactAdress(this.getUcontactAdress());
		user.setUzip(this.getUzip());
		user.setUwangwangNum(this.getUwangwangNum());
		user.setUQQNum(this.getUQQNum());
		user.setUmsnNum(this.getUmsnNum());
		user.setUnote(this.getUnote());
		
		userService.modify(user);
		
	//	request.setAttribute("result",getJson(user));
		//给提交一个返回值
		request.setAttribute("result", "{success:true,message:'ok'}");
		
		return "personerProfileModifySuccess";
	}
	
	public String getUserByUid()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		String Uid = (String) session.getAttribute("Uid");
		User user = new User();
		user.setUid(Uid);
		user = userService.getUserByUid(user);
		request.setAttribute("result",getJson(user));
		
		return "personerProfileShowSuccess";
	}
	
	public String changeUserPassword()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		String Uid = (String) session.getAttribute("Uid");
		
		User user = new User();
		user.setUid(Uid);
		user.setUemail((String)session.getAttribute("Uemail"));
		user.setUpassword(this.getUpassword());
		User checkUser = userService.checkLogin(user);
		if(null==checkUser){
			request.setAttribute("flag","N");
		}else{
			userService.changePassword(user,this.getUserPasswordNew());
			request.setAttribute("flag","Y");
		}
		
		return "changePasswordResult";
	}
	
	
	public String queryUname()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		String flag = request.getParameter("flag");
		HttpSession session = request.getSession(true);
		String Uid = (String) session.getAttribute("Uid");
		User user = new User();
		user.setUid(Uid);
		user = userService.getUserByUid(user);
		
		Integral in = new Integral();
		in.setUid(Uid);
		in = integralService.getIntegralByUid(in);
		
		request.setAttribute("userTO", user);
		request.setAttribute("integralTO", in);
		if("b".equals(flag))
			return "bakAddressShowSuccess";
		
		return "transportAddressShowSuccess";
	}
	

	private String getJson(User user){
		StringBuffer jsonStr = new StringBuffer("[{");
		jsonStr.append("Uid:'").append(user.getUid()).append("',");
		jsonStr.append("Uemail:'").append(user.getUemail()).append("',");
		jsonStr.append("Upassword:'").append(user.getUpassword()).append("',");
		if (user.getUname() == null || user.getUname().equals("")) {
			jsonStr.append("Uname:'").append("").append("',");
		} else {
			jsonStr.append("Uname:'").append(user.getUname()).append("',");
		}
		if (user.getUtelephone() == null || user.getUtelephone().equals("")) {
			jsonStr.append("Utelephone:'").append("").append("',");
		} else {
			jsonStr.append("Utelephone:'").append(user.getUtelephone()).append("',");
		}
		if (user.getUcontactAdress() == null || user.getUcontactAdress().equals("")) {
			jsonStr.append("UcontactAdress:'").append("").append("',");
		} else {
			jsonStr.append("UcontactAdress:'").append(user.getUcontactAdress()).append("',");
		}
		if (user.getUzip() == null || user.getUzip().equals("")) {
			jsonStr.append("Uzip:'").append("").append("',");
		} else {
			jsonStr.append("Uzip:'").append(user.getUzip()).append("',");
		}
		if (user.getUwangwangNum() == null || user.getUwangwangNum().equals("")) {
			jsonStr.append("UwangwangNum:'").append("").append("',");
		} else {
			jsonStr.append("UwangwangNum:'").append(user.getUwangwangNum()).append("',");
		}
		if (user.getUQQNum() == null || user.getUQQNum().equals("")) {
			jsonStr.append("UQQNum:'").append("").append("',");
		} else {
			jsonStr.append("UQQNum:'").append(user.getUQQNum()).append("',");
		}
		if (user.getUmsnNum() == null || user.getUmsnNum().equals("")) {
			jsonStr.append("UmsnNum:'").append("").append("',");
		} else {
			jsonStr.append("UmsnNum:'").append(user.getUmsnNum()).append("',");
		}
		if (user.getUnote() == null || user.getUnote().equals("")) {
			jsonStr.append("Unote:'").append("");
		} else {
			jsonStr.append("Unote:'").append(user.getUzip());
		}
		jsonStr.append("'}]");
		return "{root:"+jsonStr.toString()+"}";
	}
	
	public String logout()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		//session.removeAttribute("Uemail");
		//session.removeAttribute("Uid");
		session.invalidate();
		return "logoutSuccess";
	}
	
	
	//added by gaoshuai
	private PageView pageView;

	public PageView getPageView() {
		return pageView;
	}

	public void setPageView(PageView pageView) {
		this.pageView = pageView;
	}
	
	private List<Waybill> consumptionHistory;

	public List<Waybill> getConsumptionHistory() {
		return consumptionHistory;
	}

	private String accountAction;
	public String getAccountAction() {
		return accountAction;
	}
	
	public String showConsumptionHistory() {
		
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String action = request.getParameter("action");
		
		//String currentPage = (String) request.getAttribute("currentPage");
		String currentPage = (String) request.getParameter("currentPage");
		String Uid = (String) request.getSession().getAttribute("Uid");
		QueryResult<Waybill> queryResult = null;
		if (null == currentPage) {
			// 参数1 每页显示的数目 参数2当前页
			pageView = new PageView<Waybill>(20, 1);
		} else {
			pageView = new PageView<Waybill>(20, Integer.parseInt(currentPage));// 默认是10条记录,第一页;
		}
		queryResult = userService.showConsumptionHistory(Uid, pageView
				.getFirstResult(), pageView.getMaxresult(), action);
		// queryResult=chengguoService.findAllCgProject(pageView.getFirstResult(),pageView.getMaxresult());
		pageView.setQueryResult(queryResult);// 触发生成页码等等
		request.setAttribute("pageView", pageView);
		accountAction = action;
		consumptionHistory = queryResult.getResultlist();
		return "showConsumptionHistory";
	}
	//added by gaoshuai
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public IntegralService getIntegralService() {
		return integralService;
	}

	public void setIntegralService(IntegralService integralService) {
		this.integralService = integralService;
	}
	public String getUemail() {
		return Uemail;
	}

	public void setUemail(String uemail) {
		Uemail = uemail;
	}

	public String getUpassword() {
		return Upassword;
	}

	public void setUpassword(String upassword) {
		Upassword = upassword;
	}
	public String getUid() {
		return Uid;
	}

	public void setUid(String uid) {
		Uid = uid;
	}
	public String getUreceiveId() {
		return UreceiveId;
	}
	public void setUreceiveId(String ureceiveId) {
		UreceiveId = ureceiveId;
	}
	public String getUname() {
		return Uname;
	}

	public void setUname(String uname) {
		Uname = uname;
	}

	public String getUtelephone() {
		return Utelephone;
	}

	public void setUtelephone(String utelephone) {
		Utelephone = utelephone;
	}

	public String getUcontactAdress() {
		return UcontactAdress;
	}

	public void setUcontactAdress(String ucontactAdress) {
		UcontactAdress = ucontactAdress;
	}

	public String getUzip() {
		return Uzip;
	}

	public void setUzip(String uzip) {
		Uzip = uzip;
	}

	public String getUwangwangNum() {
		return UwangwangNum;
	}

	public void setUwangwangNum(String uwangwangNum) {
		UwangwangNum = uwangwangNum;
	}

	public String getUQQNum() {
		return UQQNum;
	}

	public void setUQQNum(String uQQNum) {
		UQQNum = uQQNum;
	}

	public String getUmsnNum() {
		return UmsnNum;
	}

	public void setUmsnNum(String umsnNum) {
		UmsnNum = umsnNum;
	}

	public String getUnote() {
		return Unote;
	}

	public void setUnote(String unote) {
		Unote = unote;
	}

	private String userPasswordNew;


	public String getUserPasswordNew() {
		return userPasswordNew;
	}

	public void setUserPasswordNew(String userPasswordNew) {
		this.userPasswordNew = userPasswordNew;
	}
	public String getUregisterTime() {
		return UregisterTime;
	}

	public void setUregisterTime(String uregisterTime) {
		UregisterTime = uregisterTime;
	}
	public String getUrecommendId() {
		return UrecommendId;
	}

	public void setUrecommendId(String urecommendId) {
		UrecommendId = urecommendId;
	}

	public String getUrecommendBonusFlag() {
		return UrecommendBonusFlag;
	}

	public void setUrecommendBonusFlag(String urecommendBonusFlag) {
		UrecommendBonusFlag = urecommendBonusFlag;
	}
	public String index() {
		
		List annList = userService.getArticle("announcement", 10);
		ServletActionContext.getRequest().setAttribute("annList", annList);
		
		List newsList = userService.getArticle("news", 6);
		ServletActionContext.getRequest().setAttribute("newsList", newsList);
		
		List problemsList = userService.getArticle("problems", 6);
		ServletActionContext.getRequest().setAttribute("problemsList", problemsList);

		List newUserList = userService.getArticle("newUser", 6);
		ServletActionContext.getRequest().setAttribute("newUserList", newUserList);
		
		List discountList = userService.getArticle("discount", 6);
		ServletActionContext.getRequest().setAttribute("discountList", discountList);
		
		return "index";
		
	}
}